//
//  TFPhotoPickerCollectionViewCell.m
//  PhotoDemoProject
//
//  Created by TFAppleWork-Summer on 2016/11/15.
//  Copyright © 2016年 TFAppleWork-Summer. All rights reserved.
//

#import "TFPhotoPickerItemCollectionViewCell.h"
//工具
#import "TFPhotoHandler.h"
#import "UIColor+TFPhoto.h"
#import "TFPhotoResourceHelper.h"
//UI
#import "TFICloudDownloadView.h"
#import "TFPhotoPickerVideoInfoView.h"

@interface TFPhotoPickerItemCollectionViewCell ()<TFPhotoPickerItemModelDelegate>

@property (nonatomic, strong) TFPhotoPickerVideoInfoView *videoInfoView;

@property (nonatomic, strong) UIView *selectCoverView;

@property (nonatomic, strong) TFICloudDownloadView *iCloudDownloadView;

@property (nonatomic, strong, readwrite) UIButton *selectButton;

@end

@implementation TFPhotoPickerItemCollectionViewCell

@synthesize model = _model;
@synthesize delegate = _delegate;
@synthesize photoImageView = _photoImageView;

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.contentView.backgroundColor = [UIColor tfPhoto_hexColorWith:@"f2f2f2"];
        [self.contentView addSubview:self.photoImageView];
        [self.contentView addSubview:self.videoInfoView];
        [self.contentView addSubview:self.selectCoverView];
        [self.selectCoverView addSubview:self.selectButton];
        [self.contentView addSubview:self.iCloudDownloadView];
        //添加约束
        self.photoImageView.translatesAutoresizingMaskIntoConstraints = NO;
        self.videoInfoView.translatesAutoresizingMaskIntoConstraints = NO;
        self.iCloudDownloadView.translatesAutoresizingMaskIntoConstraints = NO;
        self.selectCoverView.translatesAutoresizingMaskIntoConstraints = NO;
        self.selectButton.translatesAutoresizingMaskIntoConstraints = NO;
        
        NSDictionary *viewDic = @{@"photoImageView":self.photoImageView,@"videoInfoView":self.videoInfoView,@"iCloudView":self.iCloudDownloadView,@"selectCoverView":self.selectCoverView};
        
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[photoImageView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[photoImageView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[videoInfoView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[videoInfoView(30.0)]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[iCloudView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[iCloudView]|" options:0 metrics:nil views:viewDic]];
        
        
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[selectCoverView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[selectCoverView]|" options:0 metrics:nil views:viewDic]];
        
        [NSLayoutConstraint constraintWithItem:self.selectButton attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.selectCoverView attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0].active = YES;
        [NSLayoutConstraint constraintWithItem:self.selectButton attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.selectCoverView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0].active = YES;
    }
    return self;
}

- (void)addSubViewContraints {
    
}

#pragma mark - view actions.

- (void)reloadCell {
    self.model.delegate = self;
    if (self.model.image==nil) {
        [[TFPhotoHandler sharedHandler] getThumbnailImageWithAsset:self.model.asset size:self.model.assetSize resultHandler:^(UIImage *image, NSDictionary *info) {
            self.model.image = image;
            self.photoImageView.image = image;
        }];
    }
    else {
        self.photoImageView.image = self.model.image;
    }
    _videoInfoView.lengthInfo = self.model.duration;
    _videoInfoView.hidden = !self.model.duration.length;
    [self doSelectWithAnimated:NO];
    if (_model.modelType==TFPhotoPickerItemModelTypeNormal) {
        _iCloudDownloadView.hidden = YES;
    }
    else {
        _iCloudDownloadView.hidden = NO;
        if (_model.modelType==TFPhotoPickerItemModelTypeDownloadImageFail) {
            [_iCloudDownloadView failAnimation];
        }
    }
    if ([self.delegate respondsToSelector:@selector(photoPickerItemCollectionViewCellDidReloadCell:)]) {
        [self.delegate photoPickerItemCollectionViewCellDidReloadCell:self];
    }
}

- (void)doSelectWithAnimated:(BOOL)animated {
    if (animated) {
        self.selectButton.transform = CGAffineTransformMakeScale(0.3, 0.3);
        [UIView animateWithDuration:0.5 delay:0.0 usingSpringWithDamping:0.55f initialSpringVelocity:0.6f options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [self handleItemSelect];
        } completion:nil];
    }
    else {
        [self handleItemSelect];
    }
}

- (void)handleItemSelect {
    self.selectButton.selected = self.model.select;
    if (self.model.select) {
        self.selectCoverView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.3];
        self.selectButton.transform = CGAffineTransformIdentity;
    }
    else {
        self.selectCoverView.backgroundColor = [UIColor clearColor];
        self.selectButton.transform = CGAffineTransformIdentity;
    }
}

- (void)selectButtonAction:(UIButton *)sender {
    //调用代理事件处理方法
    if ([self.delegate respondsToSelector:@selector(photoPickerItemCollectionViewCell:didClickSelectButton:)]) {
        [self.delegate photoPickerItemCollectionViewCell:self didClickSelectButton:sender];
    }
}

- (void)startDownloadICloudImage {
    typeof(self) __weak weakSelf = self;
    if (self.model.modelType!=TFPhotoPickerItemModelTypeDownloadingImageFromICloud) {
        _iCloudDownloadView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
        _iCloudDownloadView.hidden = NO;
        [UIView animateWithDuration:0.5 animations:^{
            weakSelf.iCloudDownloadView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        } completion:^(BOOL finished) {
            [weakSelf _startDownloadAnimation];
        }];
    }
}

- (void)_startDownloadAnimation {
    typeof(self) __weak weakSelf = self;
    [self.iCloudDownloadView startAnimationWithCompletion:^(TFICloudDownloadView *downloadView) {
        [weakSelf.model startDownloadImageFromICloud];
    }];
}

#pragma mark - TFPhotoPickerItemModelDelegate

- (void)photoPickerItemModel:(TFPhotoPickerItemModel *)model downloadingImageFromICloudWithProgress:(float)progress {
    _iCloudDownloadView.progress = progress;
}

- (void)photoPickerItemModel:(TFPhotoPickerItemModel *)model finishDownloadImageFromICloud:(UIImage *)image {
    typeof(self) __weak weakSelf = self;
    
    [_iCloudDownloadView successAnimationWithCompletion:^(TFICloudDownloadView *downloadView) {
        weakSelf.iCloudDownloadView.hidden = YES;
        [weakSelf.iCloudDownloadView recoverOriginalState];
        if ([weakSelf.delegate respondsToSelector:@selector(photoPickerItemCollectionViewCellDidFinishDownloadImageFromICloud:)]) {
            [weakSelf.delegate photoPickerItemCollectionViewCellDidFinishDownloadImageFromICloud:self];
        }
    }];
}

- (void)photoPickerItemModelFailDownloadImageFromICloud:(TFPhotoPickerItemModel *)model {
    [_iCloudDownloadView failAnimation];
}

#pragma mark - lazy load.

- (UIView *)selectCoverView {
    if (!_selectCoverView) {
        _selectCoverView = [[UIView alloc] init];
    }
    return _selectCoverView;
}

- (UIButton *)selectButton {
    if (!_selectButton) {
        _selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
        CGFloat maxPadding = 10.0;
        CGFloat minPadding = 4.0;
        _selectButton.contentEdgeInsets = UIEdgeInsetsMake(maxPadding, maxPadding, minPadding, minPadding);
        [_selectButton setImage:[TFPhotoResourceHelper imageNamed:@"photo_unselected"] forState:UIControlStateNormal];
        [_selectButton setImage:[TFPhotoResourceHelper imageNamed:@"photo_selected"] forState:UIControlStateSelected];
        [_selectButton addTarget:self action:@selector(selectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectButton;
}

- (UIImageView *)photoImageView {
    if (!_photoImageView) {
        _photoImageView = [[UIImageView alloc] init];
        _photoImageView.contentMode = UIViewContentModeScaleAspectFill;
        _photoImageView.clipsToBounds = YES;
    }
    return _photoImageView;
}

- (TFPhotoPickerVideoInfoView *)videoInfoView {
    if (!_videoInfoView) {
        _videoInfoView = [[TFPhotoPickerVideoInfoView alloc] init];
    }
    return _videoInfoView;
}

- (TFICloudDownloadView *)iCloudDownloadView {
    if (!_iCloudDownloadView) {
        _iCloudDownloadView = [[TFICloudDownloadView alloc] init];
        _iCloudDownloadView.cloudSize = CGSizeMake(60.0, 60.0);
    }
    return _iCloudDownloadView;
}

@end
